package cn.lp207663436.dynamicmanager.controller;


import cn.lp207663436.dynamicmanager.service.TestNodeService;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Set;

/**
 * <p>
 *  生产者控制器
 * </p>
 *
 * @author luopeng
 * @since 2023-07-04
 */
@RestController
@RequestMapping(value = "/dynamicmanager/testNode")
public class TestNodeController {

    @Resource
    private TestNodeService testNodeService;



    @Resource
    private DataSource dataSource;
    @Resource
    private DefaultDataSourceCreator dataSourceCreator;


    @GetMapping("list")
    public Set<String> list() {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        return ds.getDataSources().keySet();
    }

    @PostMapping("add")
    public Set<String> add(@Validated @RequestBody DataSourceProperty dto) {
//        DataSourceProperty dataSourceProperty = new DataSourceProperty();
//        BeanUtils.copyProperties(dto, dataSourceProperty);
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        DataSource dataSource = dataSourceCreator.createDataSource(dto);
        ds.addDataSource(dto.getPoolName(), dataSource);
        return ds.getDataSources().keySet();
    }

    @DeleteMapping("remove")
    public void remove(String name) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(name);
    }
    
    @GetMapping
    public Object getTestNodeList() {
        return testNodeService.list();
     }

}
